package com.king.platform.config;

import com.king.platform.component.AsyncPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableConfigurationProperties(AsyncPoolConfig.class)
@EnableAsync
public class ExecutorConfig {

  @Autowired
  AsyncPoolConfig asyncPoolConfig;

  @Bean("MyThreadPoolExecutor")
  public Executor getAsyncThreadPool() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(asyncPoolConfig.getCorePoolSize());
    executor.setMaxPoolSize(asyncPoolConfig.getMaxPoolSize());
    executor.setKeepAliveSeconds(asyncPoolConfig.getKeepAliveSeconds());
    executor.setQueueCapacity(asyncPoolConfig.getQueueCapacity());
    executor.setThreadNamePrefix("async-service");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    return executor;
  }

}
